package com.abc.filter;

import com.abc.config.PropertiesUtil;
import com.abc.config.WhiteListProperties;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class WhiteListFilter implements GlobalFilter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(WhiteListFilter.class);

    private int order;

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("WhiteListFilter ...");

        String url = exchange.getRequest().getURI().getPath();
        logger.info("白名单进入过滤器url:{}", url);
        WhiteListProperties whiteListProperties = PropertiesUtil.getWhiteListProperties();
        String[] allowPathsArrays = whiteListProperties.getAllowPaths().split("&");
        for (String allowPath : allowPathsArrays) {
            if (url.matches(allowPath)) {
                logger.info("白名单url:{}", url);
                exchange.getAttributes().put(ConstantFilter.WHITE_LIST_CONDITION, "true");
                return chain.filter(exchange);
            }
        }
        /*exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        logger.info("白名单中无此url:{}", url);
        String data = "拒绝访问，该url不在白名单中: " + url;
        DataBuffer wrap = exchange.getResponse().bufferFactory().wrap(data.getBytes());
        return exchange.getResponse().writeWith(Mono.just(wrap));*/
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return this.order;
    }


    public WhiteListFilter(int order) {
        this.order = order;
    }
}
